package org.deng.learn.netty.barrage;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;

/**
 * @author 邓力宾
 * @Desc
 * @since 2020/6/16 下午3:27
 */
public class WebsocketBarrageServerInitializer extends ChannelInitializer<SocketChannel> {

    private TextWebSocketFrameHandler webSocketFrameHandler = new TextWebSocketFrameHandler(); //使用@ChannelHandler.Sharable 注解设置成共享的
    private HttpRequestHandler requestHandler = new  HttpRequestHandler("/ws"); // 设置成共享的
    /**
     * 每次连接都会调用该方法, 每个连接都会添加新的handler对象
     * @param ch
     * @throws Exception
     */
    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        System.out.println("initChannel方法");
        ChannelPipeline pipeline = ch.pipeline();
        pipeline.addLast("http-decoder",new HttpRequestDecoder());
        pipeline.addLast("http-aggregator",new HttpObjectAggregator(65536));
        pipeline.addLast("http-encoder",new HttpResponseEncoder());
        pipeline.addLast("http-chunked",new ChunkedWriteHandler());

        pipeline.addLast("http-request",requestHandler);
        pipeline.addLast("WebSocket-protocol",new WebSocketServerProtocolHandler("/ws"));
        pipeline.addLast("WebSocket-request",webSocketFrameHandler);
    }
}
